package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 * 
 * @author w
 * @date 2025-08-03
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    /**
     * 获取所有产品数据,同步到redis
     */
    @Override
    public void syncProductList() {
        //1.调用华为
        //创建请求对象,用于查询产品列表
        ListProductsRequest request = new ListProductsRequest();
        //设置每页返回的条数
        request.setLimit(50);
        //发送请求并获取响应
        ListProductsResponse response = client.listProducts(request);
        //处理响应数据
        List<ProductSummary> products = response.getProducts();
        //如果获取的数据是空的,就返回错误
        if (CollUtil.isEmpty(products)){
            throw new BaseException("物联网接口-查询产品,同步失败!");
        }
        //2.存入Redis(直接覆盖旧的数据)
        //获取Redis的字符串操作对象,并设置键值对到Redis中
        //(常量,转换成JOSN字符串)
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));

    }

    @Override
    public List<ProductVo> getAllProduct() {
        String jsonObj = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (ObjUtil.isEmpty(jsonObj)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonObj,ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        //1.设备名称不能重复
        Long deviceNameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName()));
        if (deviceNameCount>=1){
            //抛出异常
            throw new BaseException("当前设备名称已存在!");
        }
        //2.设备唯一标识不能重复
        Long nodeCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId()));
        if (nodeCount>=1){
            //抛出异常
            throw new BaseException("当前设备标识已存在!");
        }
        //3.同一位置不能绑定相同的产品
        Long sameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getBindingLocation()), Device::getBindingLocation, dto.getBindingLocation())
                .eq(ObjectUtil.isNotEmpty(dto.getLocationType()), Device::getLocationType, dto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()), Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getProductKey()), Device::getProductKey, dto.getProductKey())
        );
        if (sameCount>=1){
            //抛出异常
            throw new BaseException("当前位置已存在相同设备!");
        }
        //4.调用华为云IOT平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        AuthInfo authInfo = new AuthInfo();
        authInfo.withSecret(UUID.randomUUID().toString().replace("-",""));
        body.withAuthInfo(authInfo);
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        request.withBody(body);

        //调用华为云
        AddDeviceResponse response = client.addDevice(request);
        String deviceId = response.getDeviceId();

        //5.将数据写入本地  dto->Device
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(authInfo.getSecret());
        save(device);

    }

    @Override
    public DeviceDetailVo querDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)){
            return null;
        }
        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        response=client.showDevice(request);

        //属性拷贝
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        detailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)){
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
           parse= parse.atZone(ZoneId.from(ZoneOffset.UTC))
                   .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                   .toLocalDateTime();
           detailVo.setActiveTime(parse);
        }
        return detailVo;

    }

    @Override
    public List<DeviceShadowVo> queryServicePropertiesd(String iotId) {
        //1.调用华为云IOT,查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        //2.查询不到,返回空
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }
        //3.转换成Vo数据
        //3.1获取属性集合信息
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //3.2 日期时区转换
        LocalDateTime localDateTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //3.3 Vo封装
        List<DeviceShadowVo> vos = new ArrayList<>();
        jsonObject.forEach((key,value)->{
            DeviceShadowVo vo=DeviceShadowVo.builder()
                    .functionId(key)
                    .value(value)
                    .eventTime(localDateTime)
                    .build();
            vos.add(vo);
        });
return vos;
    }
}
